package com.wyp168.renren_cms.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.wyp168.common.utils.R;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName OSSController
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2022/11/20 11:33
 */
@RestController
@Log4j2
@RequestMapping("/oss")
public class OSSController {

    @Value("${spring.cloud.alicloud.access-key}")
    String ACCESS_KEY;

    @Value("${spring.cloud.alicloud.secret-key}")
    String SECRET_KEY;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String ENDPOINT;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    String BUCKET_NAME;

    @Value("${spring.cloud.alicloud.oss.callbackUrl}")
    String CALLBACK_URL;




    @GetMapping("/policy/get")
    public R policy() {
        String dateFormat = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        String host = "https://" + BUCKET_NAME + "." + ENDPOINT;
        String dir = dateFormat + "/";

        // 创建ossClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessId", ACCESS_KEY);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("callback", CALLBACK_URL);
            log.info("调用oss，获取回调地址成功:{}", respMap.toString());
            return R.ok().put("data", respMap);
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }

        return R.error("获取oss上传签名失败");
    }

    @GetMapping(value = "/callback")
    public void callBack(HttpServletRequest request, HttpServletResponse response, String results,int status) throws IOException {
        String callbackFunName = request.getParameter("callback");
        if (callbackFunName == null || callbackFunName.equalsIgnoreCase("")) {
            response.getWriter().println(results);
        } else {
            response.getWriter().println(callbackFunName + "(" + results + ")");
        }

    }
}
